<template>
  <button :disabled="_disabled"
          class="count-down"
          @click="handleClick">{{_btnText}}</button>
</template>
<script>
export default {
  props: {
    second: {
      type: Number,
      default: 60,
    },
    text: {
      type: String,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 手动允许倒计时--true 需要外部调用 run 方法
    handRun: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isCountDown: false,
      btnText: "",
    };
  },
  created() {
    this.btnText = this.text;
  },
  computed: {
    _disabled() {
      return this.disabled || this.isCountDown;
    },
    _btnText() {
      return this.btnText + (this.isCountDown ? "s" : "");
    },
  },
  methods: {
    handleClick() {
      this.$emit("click", this);
      if(!this.handRun) {
        this.run()
      }
    },
    run() {
      this.btnText = 60;
      this.isCountDown = true;
      this.getTimer = setInterval(() => {
        this.btnText--;
        if (!this.btnText) {
          // this.btnText = this.text;
          this.btnText = '重新获取';
          this.isCountDown = false;
          clearInterval(this.getTimer);
          this.$emit('past')
        }
      }, 1000);
    },
  },
};
</script>
